#! /user/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/12/30 9:18 AM
# @Author  : Aman [WangSL]
# @FileName: logFilesHandle.py
# @Software: PyCharm

import config
import os
import time
import datetime
from .amanLogs import Logger
import traceback

'''
处理日志文件
'''

removeLogFilelogger = Logger(logname=config.logFilePath, loglevel=1, logger='removeOutDateSetLogFiles').getlog()

# 计算到今天的天数差值
def getDiffDaysToNow(dateStr):
    currentTime = time.localtime(time.time())
    compareTime = time.strptime(dateStr, "%Y-%m-%d")
    date1 = datetime.datetime(compareTime[0], compareTime[1], compareTime[2])
    date2 = datetime.datetime(currentTime[0], currentTime[1], currentTime[2])
    diffDays = (date2 - date1).days
    return diffDays

# 删除超过设定期限的日志文件
def removeOutDateSetLogFiles():
    filePath = config.logFileDir
    holdDays = config.logFilesHoldDays
    allLogFiles = os.listdir(filePath)
    try:
        for logFile in allLogFiles:
            logFilePath = filePath + logFile

            time_local = time.localtime(os.path.getctime(logFilePath))
            time_Ymd = time.strftime("%Y-%m-%d", time_local)
            logFileExists = getDiffDaysToNow(time_Ymd) + 1

            if isinstance(holdDays, int) and holdDays > 0:
                if os.path.exists(filePath):
                    if logFileExists > holdDays:
                        os.remove(logFilePath)
                        removeLogFilelogger.info('日志文件【%s】创建已超过【%d】天，已被删除' %(logFile, holdDays))
                    else:
                        removeLogFilelogger.info('日志文件【%s】创建不足【%d】天，不需要删除' % (logFile, holdDays))
                else:
                    removeLogFilelogger.info('日志文件【%s】不存在，删除失败！' %(logFile))
            else:
                removeLogFilelogger.info('日志文件保留天数【%s】设置异常，请检查！' %(str(holdDays)))
    except Exception:
        removeLogFilelogger.error(traceback.format_exc())


if __name__ == '__main__':
    removeOutDateSetLogFiles()
